package com.itbac.loadbalance;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 负载均衡：轮询
 * @author: BacHe
 * @email: 1218585258@qq.com
 * @Date: 2020/9/6 22:12
 */
@Component
public class RotationLoadBalancer implements LoadBalancer {
    //记录获取的次数
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance getSingleAddress(List<ServiceInstance> serviceInstances) {
        Integer count = atomicInteger.incrementAndGet();
        int size = serviceInstances.size();
        //访问的次数，对服务的数量取模
        int index =  (count % size);
        //防止index角标越界,数据重置
        if (count >= Integer.MAX_VALUE || index < 0) {
            index = 0;
            atomicInteger.set(0);
        }
        return serviceInstances.get(index);
    }

}
